package cj.com.chabaike.ui.act;


import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.support.design.widget.NavigationView;
import android.support.v4.app.FragmentTransaction;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.ViewCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Toast;

import com.balysv.materialmenu.MaterialMenuView;

import cj.com.chabaike.R;
import cj.com.chabaike.ui.act.LonginAndJoin.AboutUs;
import cj.com.chabaike.ui.act.LonginAndJoin.CollectPager;
import cj.com.chabaike.ui.act.LonginAndJoin.HistoryPager;
import cj.com.chabaike.ui.act.LonginAndJoin.LoginPager;
import cj.com.chabaike.ui.act.LonginAndJoin.SearchPager;
import cj.com.chabaike.ui.frag.MainFragment;
import cj.com.chabaike.ui.frag.RecyclerFragment1;
import cj.com.chabaike.ui.frag.Special_Detail;
import cj.com.chabaike.ui.frag.ThingDetailFragment;
import cj.com.chabaike.ui.utils.BitmapUtil;
import cj.com.chabaike.ui.utils.TransitionHelper;
import cj.com.chabaike.ui.view.CustomDrawerLayout;
import cj.com.chabaike.ui.view.draw.MDrawerArrowDrawable;

import static android.view.View.*;

public class MainPager extends TransitionHelper.BaseActivity implements RecyclerFragment1.OnFragmentInteractionListener//,WaveSwipeRefreshLayout.OnRefreshListener {
{

    //    private boolean isDrawerOpened;//判断是否打开侧栏
    // private MaterialMenuIconToolbar menuIconToolbar;//绘制动画
    public MainFragment mainFragment;
    private DrawerToggle mSlider; //三道杠
    public View fragmentBackround;
    private Toolbar mToobar;
    private CustomDrawerLayout mDrawerLayout;
    //private ActionBarDrawerToggle mDrawerToggle;
    //private NavigationView mNavigationView;
    // private MaterialMenuView homeButton;

    private int newState;

    protected static String BASE_FRAGMENT = "base_fragment";


    Handler handler;
    boolean isDetail = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.mainpager);
        mSlider = new MDrawerArrowDrawableToggle(this, this);
        fragmentBackround = findViewById(R.id.base_fragment_background);
        //mNavigationView = (NavigationView) findViewById(R.id.navigation);

        mToobar = (Toolbar) findViewById(R.id.atoolbar);
        mToobar.setTitle("");
        setSupportActionBar(mToobar);
        getSupportActionBar().setDisplayShowTitleEnabled(true);
        mDrawerLayout = (CustomDrawerLayout) findViewById(R.id.drawer_layout);
        mToobar.setNavigationIcon((Drawable) mSlider);


        initDrawerToggle();
        initBaseFragment(savedInstanceState);
        handler = new Handler();


    }

    private long exitTime = 0;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (isDetail == false) {
            if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
                if ((System.currentTimeMillis() - exitTime) > 2000) {
                    Toast.makeText(getApplicationContext(), "再按一次退出程序", Toast.LENGTH_SHORT).show();
                    exitTime = System.currentTimeMillis();
                } else {
                    finish();
                   // System.exit(0);
                }
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        if (isDetail) {
            changeSlider(false);
        }
    }


    private void initDrawerToggle() {
        mToobar.setNavigationOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                toggle();
            }
        });

        mDrawerLayout.setDrawerListener(new MyDrawerListener());


/*
        mDrawerLayout = (CustomDrawerLayout) findViewById(R.id.drawer_layout);
        mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, mToobar, R.string.app_name, R.string.app_name);
        mDrawerLayout.setDrawerListener(mDrawerToggle);
        mDrawerToggle.syncState();*/
        // mDrawerLayout.setDrawerListener(new   MyDrawerListener());
    }

   //三道杠


    private void initMatrialDrawerToggle() {

        isDetail = true;
        //mSlider = new MDrawerArrowDrawableToggle(this, this);
        // mToobar.setNavigationIcon((Drawable) mSlider);
        //  mSlider.setPosition(1);//设置三道杠变箭头

        changeSlider(true);
        // mDrawerLayout = (CustomDrawerLayout) findViewById(R.id.drawer_layout);
        mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
        mToobar.setNavigationOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {

                // mSlider.setPosition(0);//设置三道杠变三道杠
                changeSlider(false);
                onBackPressed();
            }
        });


    }

    /**
     * @param tOrf  true从三道杠变为箭头 flase反之
     * <p/>
     * <p/>
     * *
     */
    private float state = 0;


    public void changeSlider(final boolean tOrf) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                if (tOrf) {
                    while (state < 1) {
                        state = state + 0.025f;
                        try {
                            Thread.sleep(15);

                            handler.post(new Runnable() {
                                @Override
                                public void run() {
                                    mSlider.setPosition(state);
                                }
                            });
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }

                    }
                } else {
                    while (state > 0) {
                        state = state - 0.025f;
                        try {
                            Thread.sleep(10);
                            handler.post(new Runnable() {
                                @Override
                                public void run() {
                                    mSlider.setPosition(state);
                                }
                            });
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }


                    }
                }
            }
        }).start();


    }


    public void headerClick(View view) {
        Intent intent;
        switch (view.getId()) {
            case R.id.login_in:
                intent = new Intent(MainPager.this, LoginPager.class);
                mDrawerLayout.closeDrawer(Gravity.LEFT);
                startActivity(intent);
                break;
            case R.id.join_in:
                intent = new Intent(MainPager.this, LoginPager.class);
                mDrawerLayout.closeDrawer(Gravity.LEFT);
                startActivity(intent);
                break;
            case R.id.collect:
                intent = new Intent(MainPager.this, CollectPager.class);
                startActivity(intent);
                break;
            case R.id.search_bar:
                intent = new Intent(MainPager.this, SearchPager.class);
                startActivity(intent);
                break;
            case R.id.about:
                intent = new Intent(MainPager.this, AboutUs.class);
                startActivity(intent);
                break;
            case R.id.history:
                intent = new Intent(MainPager.this, HistoryPager.class);
                startActivity(intent);
                break;
            case R.id.version:
                Toast.makeText(this, "当前已是最新版本", Toast.LENGTH_SHORT).show();
                break;
            case R.id.offline:
                Toast.makeText(this, "此功能尚未完善", Toast.LENGTH_SHORT).show();
                break;
            case R.id.clean:
                Toast.makeText(this, "此功能尚未完善", Toast.LENGTH_SHORT).show();
                break;
            case R.id.scan:
                Toast.makeText(this, "此功能尚未完善", Toast.LENGTH_SHORT).show();
                break;
            case R.id.switch1:
                Toast.makeText(this, "此功能尚未完善", Toast.LENGTH_SHORT).show();
                break;
            default:
                break;

        }
    }


    /*
    private MaterialMenuDrawable.IconState currentIconState;
    public boolean animateHomeIcon(MaterialMenuDrawable.IconState iconState) {
        if (currentIconState == iconState) return false;
        currentIconState = iconState;
        homeButton.animateState(currentIconState);
      //  MaterialMenuDrawable.IconState.BURGER;
        return true;
    }

    public void setHomeIcon(MaterialMenuDrawable.IconState iconState) {
        if (currentIconState == iconState) return;
        currentIconState = iconState;
        homeButton.setState(currentIconState);
    }

//    private void initToolbar() {
//        mDrawerLayout = (CustomDrawerLayout) findViewById(R.id.drawer_layout);
//        mNavigationView = (NavigationView) findViewById(R.id.navigation);
//
//        mToobar = (Toolbar) findViewById(R.id.atoolbar);
//        mToobar.setTitle("");
//        setSupportActionBar(mToobar);
//
//        mToobar.setNavigationOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                //绘制动画的状态
//
//                if (isDrawerOpened==false) {
//                    menuIconToolbar.animatePressedState(MaterialMenuDrawable.IconState.ARROW);
//                    mDrawerLayout.openDrawer(Gravity.LEFT);
//                } else {
//                    mDrawerLayout.closeDrawer(Gravity.LEFT);
//                    menuIconToolbar.animatePressedState(MaterialMenuDrawable.IconState.BURGER);
//                }
//            }
//        });
//
//
//        menuIconToolbar = new MaterialMenuIconToolbar(this, Color.WHITE, MaterialMenuDrawable.Stroke.THIN) {
//            @Override
//            public int getToolbarViewId() {
//                return R.id.atoolbar;
//            }
//        };
//        menuIconToolbar.setNeverDrawTouch(true);
//
//        mDrawerLayout.setDrawerListener(new DrawerLayout.SimpleDrawerListener() {
//            @Override
//            public void onDrawerSlide(View drawerView, float slideOffset) {
//                super.onDrawerSlide(drawerView, slideOffset);
//                menuIconToolbar.setTransformationOffset(
//                        MaterialMenuDrawable.AnimationState.BURGER_ARROW,
//                        isDrawerOpened ? 2 - slideOffset : slideOffset);
//            }
//
//            @Override
//            public void onDrawerOpened(View drawerView) {
//                isDrawerOpened = true;
//            }
//
//            @Override
//            public void onDrawerClosed(View drawerView) {
//                isDrawerOpened = false;
//            }
//
//            @Override
//            public void onDrawerStateChanged(int newState) {
//                if (newState == DrawerLayout.STATE_IDLE) {
//                    if (isDrawerOpened) {
//                        menuIconToolbar.setState(MaterialMenuDrawable.IconState.ARROW);
//                    } else {
//                        menuIconToolbar.setState(MaterialMenuDrawable.IconState.BURGER);
//                    }
//                }
//            }
//
//        });
//
//
//    }
//    @Override
//    protected void onPostCreate(Bundle savedInstanceState) {
//        super.onPostCreate(savedInstanceState);
//        isDrawerOpened = mDrawerLayout.isDrawerOpen(Gravity.LEFT); // or END, LEFT, RIGHT
//        menuIconToolbar.syncState(savedInstanceState);
//    }
//    @Override
//    public void onSaveInstanceState(Bundle outState) {
//        super.onSaveInstanceState(outState);
//        menuIconToolbar.onSaveInstanceState(outState);
//    }


    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();


    }

    /**
     * *******************方法调用区*******************************
     */
    public void openOrCloseDrawerToggle(boolean openOrColse) {
        // mDrawerToggle.onDrawerOpened();

    }

    private void toggle() {
        // if (mDrawerLayout.isDrawerVisible(GravityCompat.START))
        if (mDrawerLayout.isDrawerOpen(GravityCompat.START)) {
            //Toast.makeText(this,"关闭侧拉界面",Toast.LENGTH_SHORT ).show();
            mDrawerLayout.closeDrawer(Gravity.LEFT);
        } else {
            // Toast.makeText(this,"打开侧拉界面",Toast.LENGTH_SHORT).show();
            mDrawerLayout.openDrawer(Gravity.LEFT);
        }


    }


    private void initBaseFragment(Bundle savedInstanceState) {
        //apply background bitmap if we have one
        if (getIntent().hasExtra("bitmap_id")) {
            fragmentBackround.setBackground(new BitmapDrawable(getResources(), BitmapUtil.fetchBitmapFromIntent(getIntent())));
        }

        Fragment fragment = null;
        if (savedInstanceState != null) {
            fragment = getSupportFragmentManager().findFragmentByTag(BASE_FRAGMENT);
        }
        if (fragment == null) fragment = getBaseFragment();
        setBaseFragment(fragment);


    }

    protected Fragment getBaseFragment() {
        int fragmentResourceId = getIntent().getIntExtra("fragment_resource_id", R.layout.mfrag1);
        switch (fragmentResourceId) {
            case R.layout.mfrag1:
            default:

                return new MainFragment();
            case R.layout.fragment_thing_detail:
                initMatrialDrawerToggle();
                return ThingDetailFragment.create();

            case R.layout.special_detail_pager:
                initMatrialDrawerToggle();
                return new Special_Detail();
            //case R.layout.fragment_overaly:
            // return new OverlayFragment();
        }
    }


    public MainFragment getMainFragment() {


        return mainFragment;
    }

    public void setBaseFragment(Fragment fragment) {
        if (fragment == null) return;
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        transaction.replace(R.id.main_fragment, fragment, BASE_FRAGMENT);
        transaction.commit();
    }


    public static MainPager of(Activity activity) {
        return (MainPager) activity;
    }


    @Override
    public void onFragmentInteraction(Uri uri) {

    }


    /**
     * ***********************内部类区**********************************
     */


    public static interface DrawerToggle {

        public void setPosition(float position);

        public float getPosition();
    }


    public static class MDrawerArrowDrawableToggle extends MDrawerArrowDrawable
            implements DrawerToggle {

        private final Activity mActivity;

        public MDrawerArrowDrawableToggle(Activity activity, Context themedContext) {
            super(themedContext);
            mActivity = activity;
        }

        public void setPosition(float position) {
            if (position == 1f) {
                setVerticalMirror(true);
            } else if (position == 0f) {
                setVerticalMirror(false);
            }
            super.setProgress(position);
        }

        public boolean isLayoutRtl() {
            return ViewCompat.getLayoutDirection(mActivity.getWindow().getDecorView())
                    == ViewCompat.LAYOUT_DIRECTION_RTL;
        }

        public float getPosition() {
            return super.getProgress();
        }
    }

    private class MyDrawerListener implements DrawerLayout.DrawerListener {
        @Override
        public void onDrawerOpened(View drawerView) {// 打开drawer
            mSlider.setPosition(1);
        }

        @Override
        public void onDrawerClosed(View drawerView) {// 关闭drawer
            mSlider.setPosition(0);
        }

        @Override
        public void onDrawerSlide(View drawerView, float slideOffset) {// drawer滑动的回调
            //Log.w("onDrawerSlide","" + slideOffset);
            mSlider.setPosition(Math.min(1f, Math.max(0, slideOffset)));
        }

        @Override
        public void onDrawerStateChanged(int newState) {// drawer状态改变的回调
        }

    }

}

